package com.jorado.metrics.type;

import com.jorado.metrics.util.LabelHelp;
import com.jorado.metrics.util.VersionHelp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;

public final class Histogram {

    public static final Logger logger = LoggerFactory.getLogger(Histogram.class);

    private ConcurrentHashMap<String, io.prometheus.client.Histogram> HISTOGRAM = new ConcurrentHashMap<String, io.prometheus.client.Histogram>(16);

    private static Histogram INSTANCE = null;

    public static Histogram getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new Histogram();
        }
        return INSTANCE;
    }

    public void register(String name, String help, String... labels) {
        register(name, help, null, labels);
    }

    public void register(String name, String help, double[] doubles, String... labels) {
        if (HISTOGRAM.containsKey(name)) {
            logger.error("name of " + name + " is already exist, please try another one.");
        } else {
            help += VersionHelp.Ver;
            if (doubles == null || doubles.length == 0) {
                HISTOGRAM.put(name, io.prometheus.client.Histogram.build().name(name).labelNames(LabelHelp.addLabels(labels)).help(help).register());
            } else {
                HISTOGRAM.put(name, io.prometheus.client.Histogram.build().name(name).buckets(doubles).labelNames(LabelHelp.addLabels(labels)).help(help).register());
            }
        }
    }

    public void observe(String name, double amt, String... labelValues) {
        try {
            io.prometheus.client.Histogram histogram = HISTOGRAM.get(name);
            if (histogram != null) {
                histogram.labels(LabelHelp.addValues(labelValues)).observe(amt);
            } else {
                logger.error("metrics histogram is null. name: " + name);
            }
        } catch (Exception e) {
            logger.error("observe", e);
        }
    }

}
